package util;

import java.util.Random;

public class SelectUtils {

    // 轮盘赌选择
    public static int rouletteSelectOperator(double[] weight, Random random) {
        double sum = 0;
        for (double s : weight) {
            sum += s;
        }

        int len = weight.length;
        double[] cumulativeProbability = new double[len];
        for (int i = 0; i < len; i++) {
            cumulativeProbability[i] = weight[i] / sum;
            if (i - 1 >= 0) {
                cumulativeProbability[i] += cumulativeProbability[i - 1];
            }
        }

        for (int i = 0; i < len; i++) {
            if (random.nextDouble() <= cumulativeProbability[i]) {
                return i;
            }
        }
        return 0;
    }
}
